java如何实现文件上传和下载的功能

2024-10-31 13:20:53
推荐回答(2个)
回答(1):

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jspsmart.upload.*;
import net.sf.json.JSONObject;
import action.StudentAction;
public class UploadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
boolean result=true;
SmartUpload mySmartUpload=new SmartUpload();
mySmartUpload.initialize(this.getServletConfig(), request,response);
mySmartUpload.setTotalMaxFileSize(50*1024*1024);//大小限制
mySmartUpload.setAllowedFilesList("doc,docx");//后缀名限制
try {
mySmartUpload.upload();
com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0);
myFile.saveAs("/file/"+1+".doc");//保存目录
} catch (SmartUploadException e) {
e.printStackTrace();result=false;
}
//*****************************//
response.setContentType("text/html;charset=UTF-8");
response.setHeader("Cache-Control","no-cache");
PrintWriter out = response.getWriter();
out.print(result);
out.flush();
out.close();
}
}

//我这是ajax方式的,不想这样,把//**********************//以下部分修改就行了
//需要SmartUpload组件,去网上下个就行了,也有介绍的

回答(2):

自定义一个http请求。把文件内容包在http中发送想服务器即可!