sending side- It is in android and it is part of AsyncTask, doInBackground. Basically, it will send file name, size, and image data to serverside.
InetAddress serverIP = InetAddress.getByName(IP);
Socket client = new Socket(serverIP,SERVER_PORT);
System.out.println("Connected to Server\n");
System.out.println(imgFile.length());
//sending name of the file
PrintWriter name = new PrintWriter(new OutputStreamWriter(client.getOutputStream()),true);
name.println(fileName);
name.flush();
//sending size of the file
name.println(imgFile.length());
name.flush();
//sending body
DataInputStream imgBodyIn = new DataInputStream(new FileInputStream(imgFile));
DataOutputStream imgBodyOut = new DataOutputStream(client.getOutputStream());
byte[] buffer = new byte[BUFFER_SIZE];
int len;
long filesize = imgFile.length();
while(filesize >=0&& (len=imgBodyIn.read(buffer,0,(int)Math.min(buffer.length,filesize)))>0){
imgBodyOut.write(buffer,0,len);
filesize-=len;
}
name.close();
imgBodyIn.close();
imgBodyOut.flush();
imgBodyOut.close();
client.close();
Receiving side
//receiving name
BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
String name = in.readLine();
System.out.println("Name of the File : " + name+".JPG");
//receiveing size info
String size = in.readLine();
System.out.println("Size of the File :"+size +"bytes");
//storing file
File f = new File("/home/ubuntu", name+".JPG");
FileOutputStream output = new FileOutputStream(f);
int len=0;
long received=0;
byte[] buf = new byte[BUFFER];
while(received<=Long.parseLong(size)&&(len=sock.getInputStream().read(buf))>0)
{
output.write(buf,0,len);
received +=len;
System.out.print("Receiving.."+received +"/"+size+"\r");
}
output.flush();
output.close();
in.close();
System.out.println("\n"+name+".JPG received");
System.out.println("Size received :"+f.length()+"bytes");
when I tried to send a file, correct size info and name are transferred. However, I could not receive full file; some bytes are missing. Buffer size I am using is 1024.
Sample run :
Waiting for client to connect..
Client Accepted
Name of the File : P1011474.JPG
Size of the File :714438bytes
Receiving..712997/714438
P1011474.JPG received
Size received :712997bytes
socket closed
Most likely it's the BufferedReader on the receiving side, which contains an internal buffer to improve performance when reading from the stream. See Javadoc:
Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
So it won't just read the two lines, but might as well read ahead after your two lines. Therefore a part of the binary image you appended might be buffered as well. When you then try to read the binary data directly from the InputStream wrapped with DataInputStream, you won't receive the bytes which were already buffered in the BufferedReader instance.
I would suggest, that you don't use a PrintWriter but instead write the file name and length directly using methods from DataOutputStream, e.g.:
out.writeUTF(fileName);
out.writeLong(imgFile.length());
On the receiving side use the read* methods of DataInputStream, instead of the BufferedReader. If you want to buffer, wrap the socket InputStream in a BufferedInputStream:
DataInputStream dis = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
String fileName = dis.readUTF();
long fileLength = dis.readLong();
// now read file contents from stream
And by the way, you don't have to do:
imgBodyIn.read(buffer,0,(int)Math.min(buffer.length,filesize))
when reading in the image from a file, just do:
imgBodyIn.read(buffer, 0, buffer.length)
The end of stream/file is recognized and read() will return the length of bytes read, so you don't need to do Math.min().
Related
I'm using sendgrid to send mails with attachments. But seems like excel file is corrupted in the mail. This is the code I'm using
byte[] byteData = System.Text.Encoding.ASCII.GetBytes(File.ReadAllText(#"fullpath\test.xlsx"));
msg.Attachments = new List<SendGrid.Helpers.Mail.Attachment>
{
new SendGrid.Helpers.Mail.Attachment
{
Content = Convert.ToBase64String(byteData),
Filename = "test.xlsx",
Type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
Disposition = "attachment"
}
};
On opening of excel file, I'm getting a popup "We found a problem with content...If you trust click "Yes". On Yes, Excel cannot open this file. Can anyone please help me on this
#Sendgrid
Twilio SendGrid developer evangelist here.
I think the issue may be that you are getting the byte data by reading the file as text and then converting that text to bytes through the lens of ASCII encoding. It may work better to just read the file as bytes initially.
Try:
byte[] byteData = File.ReadAllBytes(#"fullpath\test.xlsx");
msg.Attachments = new List<SendGrid.Helpers.Mail.Attachment>
{
new SendGrid.Helpers.Mail.Attachment
{
Content = Convert.ToBase64String(byteData),
Filename = "test.xlsx",
Type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
Disposition = "attachment"
}
};
Try below
msg.AddAttachment("test.xlsx"); // Physical file path
Make assure file path is relevant
or You try with Bytes as well,
var bytes = File.ReadAllBytes(filePath);
var file = Convert.ToBase64String(bytes);
msg.AddAttachment("Name.xls", file);
I need to sort some Russian text file and when I try to read the strings and print them out, they all appear garbled and like boxes. Looks like there is no Russian support for my eclipse. I downloaded Language packs plug in but I can't figure out how to install it.
Help required please.
FileInputStream fstream = new FileInputStream("c:\\textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
ArrayList<String> allLines = new ArrayList<String>();
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
allLines.add(strLine);
System.out.println(strLine);
}
How can you be sure it's an eclipse problem? It could be:
The encoding of the text file
The method you used to read the text file (eg: InputStreamReader uses default charset unless you explicitly specify it on the constructor)
The method you used to store the text file in memory
The method you used to print the text
The method you used to view the printed text
I am building my HTTP WEB SERVER in JAVA.
If client request any file and that file is on that place in server, then server gives that file to client. I also made this code, and it works fine.
The part of code, that shows above functionality,
File targ = [CONTAINS ONE FILE]
PrintStream ps;
InputStream is = new FileInputStream(targ.getAbsolutePath());
while ((n = is.read(buf)) > 0) {
System.out.println(n);
ps.write(buf, 0, n);
}
But now to make my code optimized, I replace this code with below code,
InputStream is = null;
BufferedReader reader = null;
String output = null;
is = new FileInputStream(targ.getAbsolutePath());
reader = new BufferedReader(new InputStreamReader(is));
while( (output = reader.readLine()) != null) {
System.out.println("new line");
//System.out.println(output);
ps.print(output);
}
But it sometimes shows one error Why code shows "Error 354 (net::ERR_CONTENT_LENGTH_MISMATCH): The server unexpectedly closed the connection.". I didn't understand, why it shows this error. This error is very weird, because server shows 200 code, that means, that file is there.
Help me please.
Edit no. 1
char[] buffer = new char[1024*16];
int k = reader.read(buffer);
System.out.println("size : " + k);
do {
System.out.println("\tsize is : " + k);
//System.out.println(output);
ps.println(buffer);
}while( (k = reader.read(buffer)) != -1 );
This prints all the file, but for bigger files, it shows unreadable characters.
It shows below output (Snapshot of client browser)
You do output = reader.readLine() to get the data, which omits the newline characters. Then you ps.print(output), so the newline characters are not sent to the client.
Say you read this
Hello\r\n
World\r\n
Then you send this:
Content-length: 14
HelloWorld
And then close the connection, confusing the browser as it still was waiting for the other 4 bytes.
I guess you'll have to use ps.println(output).
You would have seen this if you were monitoring the network traffic, which can prove quite useful when writing or debugging a server that is supposed to communicate using the network.
Anyway this will cause trouble if the newlines of the file and the system have a mismatch (\n vs \r\n). Say you have this file:
Hello\r\n
World\r\n
Its length is 14 bytes. However when your system treats a newline when printing as \n, your code with println() will print this:
Hello\n
World\n
Which is 12 bytes, not 14. You better just print what you read.
I am new to j2me Mobile Applications. I have a college project to be done within a month. I need some basic idea of how it can be done. I am using Netbeans 6.8 j2me platform.
I have to create source, destination and many intermediate nodes(mobile phones). A file has to be sent(am using Bluetooth) from source to destination via several intermediate nodes. The file can be split into chunks and can also be sub-divided at any level.
http://imageshack.us/photo/my-images/692/parallelism.jpg/
This is how it should work:
Initially, the source sends simple objects of a Class(present in all nodes) to destination via several paths. Every node will be updating the object by including its Bluetooth address and passes it to the next node. When it reaches the destination, the same object is sent back to the source. The source identifies some of the optimal paths and uses them for file transfer.
The source splits the file and send them to the nearest nodes. The intermediate nodes can also split and send the divided parts.
When all the parts reach the destination, they are joined and the file is reconstructed.
I created separate netbeans project for source, destination and intermediate node.
Splitting : I did splitting successfully by converting the file into byte array and creating files using File connection & outputstream
public void splitfiles(int len)
{
String url="file:///root1/testfile.jpg";
// int len = 102400;
byte buffer[] = new byte[size];
int count = 0;
try
{
FileConnection fconi = (FileConnection)Connector.open(url,Connector.READ);
InputStream fis = fconi.openInputStream();
while (true)
{
int i = fis.read(buffer, 0, len); //creating byte array of size "len" bytes
if (i == -1)
break;
++count;
String filename ="file:///root1/testfile.part" + count;
FileConnection fcono = (FileConnection)Connector.open(filename,Connector.READ_WRITE);
if (!fcono.exists())
fcono.create();
OutputStream fos = fcono.openOutputStream();
fos.write(buffer, 0, i); //creating files out of byte array "buffer"
fos.close();
fcono.close();
}
}
catch(Exception e)
{ }
}
Please tell me how to rejoin the files.(I rejoined them using java class "RandomAcessFile" which is not present in j2me).
I tried in the following way
while(number of chunks)
{
read a single file in inputstream (files are read one after the other)
copy it to a byte array and flush inputstream
write it to ouputstream
}
copy outputstream to a file
flush outputstream
Please give me some idea about
how to rejoin the chunks in j2me
How to pass object of a class via bluetooth
I've got an Excel file that's built using OpenXML 2 and I want to send it as an email attachment. e.g.
System.IO.MemoryStream stream = new System.IO.MemoryStream();
SpreadsheetDocument package = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook))
AddParts(package); //created using document reflector
Saving the spreadsheet to a temp file using
stream.WriteTo(new System.IO.FileStream(#"c:\test.xlsx", System.IO.FileMode.Create));
works fine. But trying to send the stream directly as an email attachment fails - just get an empty file attached to the email when I do
System.Net.Mail.Attachment file = new System.Net.Mail.Attachment(stream, "MobileBill.xlsx", "application/vnd.ms-excel");
Anbody know how to do this?
Ok, I got this working, though through some effort. To create the stream:
MemoryStream stream = new MemoryStream();
using (SpreadsheetDocument package = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook))
{
Excel.CreateSpreadsheet(package, Excel_Methods.CreateSpotQuoteOut(), true);
}
stream.Seek(0, SeekOrigin.Begin);
System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(stream, "spreadsheet.xlsx");
attach.ContentDisposition.CreationDate = DateTime.Now;
attach.ContentDisposition.ModificationDate = DateTime.Now;
attach.ContentDisposition.Inline = false;
attach.ContentDisposition.Size = stream.Length;
attach.ContentType.MediaType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Also, I found that mine were not being sent right after I created them, and the reason for that is "standalone=yes" was not being added to the xml declaration of all the pages, so in my AddParts function, after adding the parts, I passed them into this function:
private static void AddXMLStandalone(OpenXmlPart part)
{
System.IO.StreamWriter writer = new System.IO.StreamWriter(part.GetStream());
XmlDocument doc = new XmlDocument();
doc.Load(part.GetStream());
doc.InnerXml = doc.InnerXml.Substring(doc.InnerXml.IndexOf("?>") + 2);
doc.InnerXml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + doc.InnerXml;
part.GetStream().SetLength(doc.InnerXml.Length);
doc.Save(writer);
writer.Flush();
writer.Close();
}
Good luck!
do this:
System.Net.Mail.Attachment file = new System.Net.Mail.Attachment(new MemoryStream(stream.ToArray()), "MobileBill.xlsx", "application/vnd.ms-excel");
Apparently the memory stream doesn't get flushed or something
For your "content unreadable" problem, make sure to Save() your Workbooks and Worksheets and enclose your SpreadsheetDocument in a using statement to ensure all packages and zipped streams are flushed, closed and so on.
System.IO.MemoryStream stream = new System.IO.MemoryStream();
using (SpreadsheetDocument package = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook)))
{
AddParts(package);
//Save if AddParts hasn't done it
}
System.Net.Mail.Attachment file = ...
Thinking out load: could it be, that the Attachment class expects to read from the current possition in the provided stream? If this is the case, you would probably have to "seek" back to the beginning of the stream, before feeding it to the Attachment constructor:
AddParts(package); //created using document reflector
stream.Seek(0, SeekOrigin.Begin);
System.Net.Mail.Attachment file = new System.Net.Mail.Attachment(stream, "MobileBill.xlsx", "application/vnd.ms-excel");