Java – spring: file upload restful Web Service
•
Java
I am using spring 4.0 to create a PoC for restful web services
@RequestMapping(value="/getcontent/file",method=RequestMapping.post)
public String getFileContents(@RequestParam("fileName",required=false) String fileName){
logger.info("initialization of object");
//----------------------------------------
System.out.Println("name of File : " + fileName);
//----------------------------------------
}
This works, but if I want to pass byte stream or file object functions, can I write this function with these parameters? And how do I write the client to provide a pass byte stream?
@RequestMapping(value="/getcontent/file",method=RequestMapping.post)
public String getFileContents(@RequestParam("file",required=false) byte [] fileName){
//---------------------
//
}
I tried this code, but got 415 errors
@RequestMapping(value = "/getcontent/file",method = RequestMethod.POST,consumes="multipart/form-data")
public @ResponseBody String getContentFromBytes(@RequestBody MultipartFormDataInput input,Model model) {
logger.info("Get Content. ");
//------------
}
Client code – using Apache httpclient
private static void executeClient() {
HttpClient client = new DefaultHttpClient();
HttpPost postReqeust = new HttpPost(SERVER_URI + "/file");
try{
// Set VarIoUs Attributes
multipartentity multipartentity = new multipartentity();
multipartentity.addPart("fileType",new StringBody("DOCX"));
FileBody fileBody = new FileBody(new File("D:\\demo.docx"),"application/octect-stream");
// prepare payload
multipartentity.addPart("attachment",fileBody);
//Set to request body
postReqeust.setEntity(multipartentity);
HttpResponse response = client.execute(postReqeust) ;
//Verify response if any
if (response != null)
{
System.out.println(response.getStatusLine().getStatusCode());
}
}
catch(Exception ex){
ex.printStackTrace();
}
Solution
You can create a rest service as shown below
@RequestMapping(value="/upload",method=RequestMethod.POST)
public @ResponseBody String handleFileUpload(
@RequestParam("file") multipartfile file){
String name = "test11";
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
bufferedoutputstream stream =
new bufferedoutputstream(new FileOutputStream(new File(name + "-uploaded")));
stream.write(bytes);
stream.close();
return "You successfully uploaded " + name + " into " + name + "-uploaded !";
} catch (Exception e) {
return "You Failed to upload " + name + " => " + e.getMessage();
}
} else {
return "You Failed to upload " + name + " because the file was empty.";
}
}
The client does the following
import java.io.File;
import org.apache.http.httpentity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.multipartentity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;
public class Test {
public static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION,HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("http://localhost:8080/upload");
File file = new File("C:\\Users\\Kamal\\Desktop\\PDFServlet1.pdf");
multipartentity mpEntity = new multipartentity();
ContentBody cbFile = new FileBody(file,"multipart/form-data");
mpEntity.addPart("file",cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
httpentity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
}
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
