Reputation: 830
I have a task. Upload on http server part of a file (I must skip beginning of the file).
How can I do it. Do you know good solution?
Can I use my own solution? Is it safe?
My solution. I made subclass of FileEntity that gives file stream and skips beginning of the file.
I put my entity to request.
HttpPut request = new HttpPut(this.uri);
request.setEntity(new FileOfsetEntity(new File(getDestination()), "binary/octet-stream", ofset));
My FileOfsetEntity skips begining of the file.
class FileOfsetEntity extends FileEntity {
long ofset = 0;
public FileOfsetEntity(File file, String contentType, long ofset) {
super(file, contentType);
this.ofset = ofset;
}
@Override
public long getContentLength() {
return this.file.length() - ofset;
}
@Override
public InputStream getContent() throws IOException {
FileInputStream in = new FileInputStream(this.file);
long skiped = in.skip(ofset);
Log.w("FileOfsetEntity.getContent","skiped = " + skiped);
return in;
}
@Override
public void writeTo(final OutputStream outstream) throws IOException {
if (outstream == null) {
throw new IllegalArgumentException("Output stream may not be null");
}
InputStream instream = new FileInputStream(this.file);
long skiped = instream.skip(ofset);
Log.w("FileOfsetEntity.writeTo","skiped = " + skiped);
try {
byte[] tmp = new byte[4096];
int l;
long readed = skiped;
while ((l = instream.read(tmp)) != -1) {
readed += l;
outstream.write(tmp, 0, l);
Log.v("FileOfsetEntity.writeTo",file.getAbsolutePath() + " readed = " + readed + " skiped = " + skiped);
}
outstream.flush();
} finally {
instream.close();
} }}
Upvotes: 0
Views: 845
Reputation: 2415
I am not sure this may fail or go through.
I would suggest, a different way of doing this. I presume that you know the office before uploading.
Here is a link to upload file to server.
In this code, move your offset and then start writing it into the stream.
Upvotes: 1