日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java restful文件传输_java中使用restful web service来传输文件

發布時間:2025/3/12 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java restful文件传输_java中使用restful web service来传输文件 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

【1】上傳大文件:

前端頁面:

1)同步上傳:

2)異步上傳:

異步上傳文件

上傳文件:

function doUpload() {

// var formData = new FormData($("#uploadForm")[0]);

var formData = new FormData()

formData.append("targetFile",$("#sendfile"));

formData.append("userName","test-username");

$.ajax({

url: 'http://localhost:8081/webProject/api/file/uploadFile' ,

type: 'POST',

data: formData,

async: false,

cache: false,

contentType: false,

processData: false,

dataType:'json',

success: function (data) {

alert(data);

}

});

}

后端:

web.xml

CXFServlet

org.apache.cxf.transport.servlet.CXFServlet

1

CXFServlet

/api/*

Spring配置文件:

接口:

import org.apache.cxf.jaxrs.ext.multipart.Attachment;

import org.apache.cxf.jaxrs.ext.multipart.Multipart;

@Path("")

public interface ApiFileProcessService {

[@POST](https://my.oschina.net/u/210428)

@Path("/uploadFile")

@Consumes(MediaType.MULTIPART_FORM_DATA)

public String uploadFile(@Multipart(value="targetFile")Attachment targetFile, @Multipart(value="userName")String userName);

}

實現:

import org.apache.cxf.jaxrs.ext.multipart.Attachment;

import javax.activation.DataHandler;

public class ApiFileProcessServiceImpl implements ApiFileProcessService {

@Override

public String uploadFile(Attachment targetFile, String userName) {

try {

DataHandler dataHandler = targetFile.getDataHandler();

String originalFileName = new String(dataHandler.getName().getBytes("ISO8859-1"),"UTF-8");

InputStream is = dataHandler.getInputStream();

SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");

String saveLocation = "D:\\" + df.format(new Date()) + "_" + originalFileName;

OutputStream out = new FileOutputStream(new File(saveLocation));

int read = 0;

byte[] bytes = new byte[4096];

while ((read = is.read(bytes)) != -1) {

out.write(bytes, 0, read);

}

out.flush();

out.close();

} catch (Exception e) {

e.printStackTrace();

}

return "success";

}

}

測試結果:可以輕松處理(上傳)1G以上的文件。

【2】上傳小文件:

前端頁面:

后端:

接口:

import javax.ws.rs.core.Context;

@Path("")

public interface ApiFileProcessService {

@POST

@Path("/uploadCommonFile")

@Consumes(MediaType.MULTIPART_FORM_DATA)

public String uploadCommonFile(@Context HttpServletRequest request);

}

實現:

import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class ApiFileProcessServiceImpl implements ApiFileProcessService {

@Override

public String uploadCommonFile(HttpServletRequest request) {

try {

DiskFileItemFactory factory = new DiskFileItemFactory();

ServletFileUpload fileUpload = new ServletFileUpload(factory);

List items = fileUpload.parseRequest(request);

for (FileItem item : items) {

if (!item.isFormField()) {

String originalFileName = item.getName();

SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");

String saveLocation = "D:\\" + df.format(new Date()) + "_" + originalFileName;

File picFile = new File(saveLocation);

item.write(picFile);

}

}

} catch (Exception e) {

e.printStackTrace();

}

return "success";

}

}

注意:此方法僅適合上傳小文件。

【3】下載文件

case1:

接口:

import javax.ws.rs.GET;

import javax.ws.rs.QueryParam;

@Path("")

public interface ApiFileProcessService {

@GET

@Path("/downloadTemplate")

public Response downloadTemplate(@QueryParam("templateName")templateName );

}

實現:

import javax.ws.rs.core.Response;

import javax.ws.rs.core.Response.ResponseBuilder;

public class ApiFileProcessServiceImpl implements ApiFileProcessService {

@Override

public Response downloadTemplate(String templateName) {

File file = null;

String fileName = null;

try {

String applicationPath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath();

file = new File(applicationPath + "/" + templateName);

fileName = URLEncoder.encode(templateName, "UTF-8"); // 如果不進行編碼,則下載下來的文件名稱是亂碼

} catch (Exception e) {

e.printStackTrace();

return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();

}

ResponseBuilder response = Response.ok((Object) file);

response.header("Content-Disposition", "attachment; filename=" + fileName);

return response.build();

}

}

case2:

接口:

import javax.ws.rs.*;

import javax.ws.rs.core.Context;

@GET

@Path("/exportTest")

@Produces("application/vnd.ms-excel")

public Response exportTest(@FormParam("str") String str, @Context HttpServletResponse response);

實現:

import javax.ws.rs.core.Response;

import javax.servlet.http.HttpServletResponse;

@Override

public Response exportTest(String str, HttpServletResponse response) {

try {

ServletOutputStream outputStream = response.getOutputStream();

SXSSFWorkbook wb = new SXSSFWorkbook();

wb.setCompressTempFiles(true);

Sheet sheet = wb.createSheet("sheet0");

Row row = sheet.createRow(0);

row.createCell(0).setCellValue("hahaha");

wb.write(outputStream);

response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("中文名字.xlsx", "UTF-8"));

response.setContentType("application/vnd.ms-excel");

outputStream.close();

} catch (IOException e) {

e.printStackTrace();

}

return null;

}

總結

以上是生活随笔為你收集整理的java restful文件传输_java中使用restful web service来传输文件的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。